import { sHost, configExpires } from '../config'
import moment from 'moment'
import Cookies from 'js-cookie'
import { usersInfo } from '@/api/login'
import { encrypt } from '@/utils/rsaEncrypt'


export function awaitWrap(promise) {
    return promise
        .then(data => [null, data])
        .catch(err => [err, null])
}
//获取cookie、
export function getCookie(name) {
    // var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    // console.log(arr)
    // console.log(document.cookie.match(reg))
    // if (arr = document.cookie.match(reg))
    //     return (arr[2]);
    // else
    //     return null;
    var strcookie = document.cookie;//获取cookie字符串
    var arrcookie = strcookie.split("; ");//分割
    //遍历匹配
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) {
            return arr[1];
        }
    }
    return "";
}
//设置cookie
export function setCookie(c_name, value, expiredays) {
    // var exdate = new Date();
    // let host = location.host.split('.')
    let domain = null
    // if (host.length >= 3 && !testHost()) {
    //     domain = location.host.replace(host[0], '')

    // }
    // if (host.length == 2) {
    //     domain = '.' + location.host
    // }
    // exdate.setTime(exdate.getTime() + expiredays);
    // document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ';domain=' + domain;
    // alert(c_name)
    // alert(value)
    let expires = expiredays || new Date(new Date().getTime() + 1000 * configExpires)
    console.log('expires', expires);
    Cookies.set(c_name, value, { expires, domain })
}
// 删除cookie
export function removeCookie(name) {

    let host = location.host.split('.')
    let domain = null
    if (host.length >= 3 && !testHost()) {
        domain = location.host.replace(host[0], '')
    }
    if (host.length == 2) {
        domain = '.' + location.host
    }
    Cookies.remove(name, { domain })
    // var exp = new Date();
    // exp.setTime(exp.getTime() - 1);
    // var cval = getCookie(name);
    // console.log(cval)
    // console.log(Cookies)
    // if (cval != null)
    //     document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
export function uuid() {
    var s = []
    var hexDigits = '0123456789abcdef'
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)// bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-'
    var uuid = s.join('')
    return uuid.toUpperCase()
}
// 格式化时间
export function formatTime(str, format = 'YYYY-MM-DD HH:mm:ss') {
    return moment(str).format(format)
}
// 判断是否为 序列号的JSON
export function isStringifyJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            return false;
        }
    }
}

/**
 * 字节转换为其它单位显示
 */
export function byteToOther(s) {
    let size = "177784382";
    if (s && typeof (s) == 'number') {
        if (s < 0.1 * 1024) {                            //小于0.1KB，则转化成B
            size = s.toFixed(2) + "B"
        } else if (s < 0.1 * 1024 * 1024) {               //小于0.1MB，则转化成KB
            size = (s / 1024).toFixed(2) + "KB"
        } else if (s < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB

            size = (s / (1024 * 1024)).toFixed(2) + "MB"
        } else {                                         //其他转化成GB
            size = (s / (1024 * 1024 * 1024)).toFixed(2) + "GB"
        }
        let sizeStr = size + "";                        //转成字符串
        let index = sizeStr.indexOf(".");               //获取小数点处的索引
        let dou = sizeStr.substr(index + 1, 2)          //获取小数点后两位的值
        if (dou == "00") {                                //判断后两位是否为00，如果是则删除00               
            return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
        }
    }
    return size;
}

// socket方法
export class socketClient {
    constructor(o) {
        this.websock = null
        this.againTime = null
        this.reconnectNum = 3
        this.lockReconnect = false
        this.isDisconnect = false
        this.o = o
    }
    initWebSocket(fn) {
        if (!this.websock) {
            let host = sHost().replace('http', 'ws')
            if (location.protocol === 'https:') {
                host = sHost().replace('https', 'wss')
            }
            this.websock = new WebSocket(`${host}${this.o.url}`);
            this.websock.onopen = this.websocketonopen()
            this.websock.onerror = e => { this.websocketonerror(e) }
            this.websock.onmessage = e => { this.websocketonmessage(e, fn) }
            this.websock.onclose = e => { this.websocketclose(e) }
        }
    }
    disconnect() {
        console.log('主动断开', this.websock)
        if (this.websock) {
            this.isDisconnect = true
            console.log('关闭socket')
            console.log(this.websock)
            this.websock.close();
            console.log(this.websock)
        }
    }
    websocketonopen() {
        console.log("WebSocket连接成功")
        this.reconnectNum = 3
        this.heartCheck().start()
    }
    websocketonerror(e) {
        if (this.o.errFn) {
            this.o.errFn(e)
        }
        this.heartCheck().start()
    }
    websocketonmessage(e, fn) {
        // console.log(e.data)
        fn(e)
        // if (this.o && this.o.msgFn && e.data !== 'hello') {
        //     this.o.msgFn(e)
        // }
        this.heartCheck().start()
    }
    websocketclose(e) {
        if (this.o.closeFn) {
            this.o.closeFn(e)
        }
        if (!this.isDisconnect) {
            this.reconnect()
        }
    }
    reconnect() {
        if (this.lockReconnect) {
            return;
        }
        this.lockReconnect = true;
        this.againTime && clearTimeout(this.againTime);
        this.againTime = setTimeout(() => {
            this.reconnectNum--
            if (this.reconnectNum === 0) {
                console.log('重连中...');
                this.lockReconnect = false;
                this.initWebSocket();
            }
        }, 4000);
    }
    heartCheck() {
        let __this = this
        return {
            timeout: 3000, //每隔三秒发送心跳
            num: 3,  //3次心跳均未响应重连
            timeoutObj: null,
            serverTimeoutObj: null,
            start: function () {
                // var _this = this;
                var _num = this.num;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                this.timeoutObj = setTimeout(function () {
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    //onmessage拿到返回的心跳就说明连接正常
                    if (!__this.isDisconnect) {
                        __this.websock.send("."); // 心跳包
                    }
                    _num--;
                    //计算答复的超时次数
                    if (_num === 0) {

                        __this.websock.colse();
                    }
                }, this.timeout)
            }
        }
    }
}



// 判断客户端平台
export function clientType() {
    var flag = '';
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        flag = 'ios'
    } else if (/(Android)/i.test(navigator.userAgent)) {
        flag = "android"
    } else {
        flag = "pc"
    }
    return flag;
}
let timer = null;
export function debounce(func, wait) {

    return function () {
        if (timer !== null) {
            clearTimeout(timer);
        }
        timer = setTimeout(func, wait);
    }
}

/*
 * 根据传入的时间计算距如今多少分钟
 * 时间仅限过去时
 * 调用 dateDiffByNowTime("2009-10-10 19:00:00")
 * 返回距今多少分钟
 * */
export function getMinutesago(date) {
    if (!date)
        return 0;
    const nowdate = new Date().getTime();
    const type1 = typeof date;
    if (type1 === 'string') {
        date = new Date(date).getTime();
    }
    else if (date.getTime()) { date = date.getTime(); }

    if (nowdate < date)  //如果传入的时间大于当前时间，则返回-1
        return 0;
    else
        return Math.floor((nowdate - date) / 60000);
}

/*
* 将日期格式为yyyy-mm-dd hh:mm:ss 格式的日期时间格式，转换为时间戳
* 传参：yyyy-mm-dd hh:mm:ss 格式的日期时间
* 返回对应时间戳
* */
export function stringToTime(string) {
    const f = string.split(' ', 2);
    const d = (f[0] ? f[0] : '').split('-', 3);
    const t = (f[1] ? f[1] : '').split(':', 3);
    return (new Date(
        parseInt(d[0], 10) || null,
        (parseInt(d[1], 10) || 1) - 1,
        parseInt(d[2], 10) || null,
        parseInt(t[0], 10) || null,
        parseInt(t[1], 10) || null,
        parseInt(t[2], 10) || null
    )).getTime();
}


// 获取info信息
export async function myInfo(__this) {

    if (__this.$msg && __this.$msg.info && __this.$msg.info.id) return __this.$msg.info

    let res = await usersInfo()
    if (res && res.data && !res.data.orgId && res.data.org_id) {
        res.data.orgId = res.data.org_id
    }
    if (res && res.data && res.data.orgId && !res.data.org_id) {
        res.data.org_id = res.data.orgId
    }
    setCookie('username', res.data.username);
    __this.$msg.info = res && res.data
    return res && res.data
    // return 123
}

// base64

export function base64() {
    var BASE64_MAPPING = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
        'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3',
        '4', '5', '6', '7', '8', '9', '+', '/'
    ];
    var URLSAFE_BASE64_MAPPING = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
        'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3',
        '4', '5', '6', '7', '8', '9', '-', '_'
    ];

    var _toBinary = function (ascii) {
        var binary = [];
        while (ascii > 0) {
            var b = ascii % 2;
            ascii = Math.floor(ascii / 2);
            binary.push(b);
        }
        binary.reverse();
        return binary;
    };

    var _toDecimal = function (binary) {
        var dec = 0;
        var p = 0;
        for (var i = binary.length - 1; i >= 0; --i) {
            var b = binary[i];
            if (b == 1) {
                dec += Math.pow(2, p);
            }
            ++p;
        }
        return dec;
    };

    var _toUTF8Binary = function (c, binaryArray) {
        var mustLen = (8 - (c + 1)) + ((c - 1) * 6);
        var fatLen = binaryArray.length;
        var diff = mustLen - fatLen;
        while (--diff >= 0) {
            binaryArray.unshift(0);
        }
        var binary = [];
        var _c = c;
        while (--_c >= 0) {
            binary.push(1);
        }
        binary.push(0);
        var i = 0, len = 8 - (c + 1);
        for (; i < len; ++i) {
            binary.push(binaryArray[i]);
        }

        for (var j = 0; j < c - 1; ++j) {
            binary.push(1);
            binary.push(0);
            var sum = 6;
            while (--sum >= 0) {
                binary.push(binaryArray[i++]);
            }
        }
        return binary;
    };

    var _toBinaryArray = function (str) {
        var binaryArray = [];
        for (var i = 0, len = str.length; i < len; ++i) {
            var unicode = str.charCodeAt(i);
            var _tmpBinary = _toBinary(unicode);
            if (unicode < 0x80) {
                var _tmpdiff = 8 - _tmpBinary.length;
                while (--_tmpdiff >= 0) {
                    _tmpBinary.unshift(0);
                }
                binaryArray = binaryArray.concat(_tmpBinary);
            } else if (unicode >= 0x80 && unicode <= 0x7FF) {
                binaryArray = binaryArray.concat(_toUTF8Binary(2, _tmpBinary));
            } else if (unicode >= 0x800 && unicode <= 0xFFFF) {//UTF-8 3byte
                binaryArray = binaryArray.concat(_toUTF8Binary(3, _tmpBinary));
            } else if (unicode >= 0x10000 && unicode <= 0x1FFFFF) {//UTF-8 4byte
                binaryArray = binaryArray.concat(_toUTF8Binary(4, _tmpBinary));
            } else if (unicode >= 0x200000 && unicode <= 0x3FFFFFF) {//UTF-8 5byte
                binaryArray = binaryArray.concat(_toUTF8Binary(5, _tmpBinary));
            } else if (unicode >= 4000000 && unicode <= 0x7FFFFFFF) {//UTF-8 6byte
                binaryArray = binaryArray.concat(_toUTF8Binary(6, _tmpBinary));
            }
        }
        return binaryArray;
    };

    var _toUnicodeStr = function (binaryArray) {
        var unicode;
        var unicodeBinary = [];
        var str = "";
        for (var i = 0, len = binaryArray.length; i < len;) {
            if (binaryArray[i] == 0) {
                unicode = _toDecimal(binaryArray.slice(i, i + 8));
                str += String.fromCharCode(unicode);
                i += 8;
            } else {
                var sum = 0;
                while (i < len) {
                    if (binaryArray[i] == 1) {
                        ++sum;
                    } else {
                        break;
                    }
                    ++i;
                }
                unicodeBinary = unicodeBinary.concat(binaryArray.slice(i + 1, i + 8 - sum));
                i += 8 - sum;
                while (sum > 1) {
                    unicodeBinary = unicodeBinary.concat(binaryArray.slice(i + 2, i + 8));
                    i += 8;
                    --sum;
                }
                unicode = _toDecimal(unicodeBinary);
                str += String.fromCharCode(unicode);
                unicodeBinary = [];
            }
        }
        return str;
    };

    var _encode = function (str, url_safe) {
        var base64_Index = [];
        var binaryArray = _toBinaryArray(str);
        var dictionary = url_safe ? URLSAFE_BASE64_MAPPING : BASE64_MAPPING;

        var extra_Zero_Count = 0;
        for (var i = 0, len = binaryArray.length; i < len; i += 6) {
            var diff = (i + 6) - len;
            if (diff == 2) {
                extra_Zero_Count = 2;
            } else if (diff == 4) {
                extra_Zero_Count = 4;
            }
            var _tmpExtra_Zero_Count = extra_Zero_Count;
            while (--_tmpExtra_Zero_Count >= 0) {
                binaryArray.push(0);
            }
            base64_Index.push(_toDecimal(binaryArray.slice(i, i + 6)));
        }

        var base64 = '';
        for (let i = 0, len = base64_Index.length; i < len; ++i) {
            base64 += dictionary[base64_Index[i]];
        }

        for (let i = 0, len = extra_Zero_Count / 2; i < len; ++i) {
            base64 += '=';
        }
        return base64;
    };

    var _decode = function (_base64Str, url_safe) {
        var _len = _base64Str.length;
        var extra_Zero_Count = 0;
        var dictionary = url_safe ? URLSAFE_BASE64_MAPPING : BASE64_MAPPING;

        if (_base64Str.charAt(_len - 1) == '=') {
            if (_base64Str.charAt(_len - 2) == '=') {//两个等号说明补了4个0
                extra_Zero_Count = 4;
                _base64Str = _base64Str.substring(0, _len - 2);
            } else {//一个等号说明补了2个0
                extra_Zero_Count = 2;
                _base64Str = _base64Str.substring(0, _len - 1);
            }
        }

        var binaryArray = [];
        for (var i = 0, len = _base64Str.length; i < len; ++i) {
            var c = _base64Str.charAt(i);
            for (var j = 0, size = dictionary.length; j < size; ++j) {
                if (c == dictionary[j]) {
                    var _tmp = _toBinary(j);
                    /*不足6位的补0*/
                    var _tmpLen = _tmp.length;
                    if (6 - _tmpLen > 0) {
                        for (var k = 6 - _tmpLen; k > 0; --k) {
                            _tmp.unshift(0);
                        }
                    }
                    binaryArray = binaryArray.concat(_tmp);
                    break;
                }
            }
        }
        if (extra_Zero_Count > 0) {
            binaryArray = binaryArray.slice(0, binaryArray.length - extra_Zero_Count);
        }
        var str = _toUnicodeStr(binaryArray);
        return str;
    };

    var __BASE64 = {
        encode: function (str) {
            return _encode(str, false);
        },
        decode: function (base64Str) {
            return _decode(base64Str, false);
        },
        urlsafe_encode: function (str) {
            return _encode(str, true);
        },
        urlsafe_decode: function (base64Str) {
            return _decode(base64Str, true);
        }
    };

    return __BASE64;
}
export function testIp(str) {
    let temp = str.split(':')[0]
    let n = 0
    temp.split('.').forEach(e => {
        if (!isNaN(e - 1)) {
            n += 1
        }
    })
    if (n == 0) {
        return false
    } else {
        return true
    }
}

export function testHost() {
    return testIp(location.host)
}

// 判断当前gateway是否为IP

export function isIpgetIp(src) {
    // let gateway = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
    // if (gateway.test(src)) {
    let p = src.split('//')[0]
    return `${p}//${src.replace('http://', '').replace('https://', '').split('/')[0]}/`
    // } else {
    // return src
    // }
}
export function countRanTime(time) {
    let convert = t => {
        let millisecond = new Date() - new Date(t)
        let hour = millisecond / 1000 / 60 / 60 >= 1 ? `${parseInt(millisecond / 1000 / 60 / 60)}小时` : ''
        let minute = millisecond / 1000 / 60 % 60 >= 1 ? `${parseInt(millisecond / 1000 / 60 % 60)}分钟` : ''
        return `${hour}${minute}`
    }
    return time ? convert(time) : ''
}
export function getDeviceId() {
    if (localStorage.getItem('_device_id')) {
        return localStorage.getItem('_device_id')
    }
    let _device_id = encodeURIComponent(encrypt(uuid()))
    localStorage.setItem('_device_id', _device_id)
    return _device_id
}

export function arrSplit(arr, N) {
    var result = [];
    for (var i = 0; i < arr.length; i += N) {
        result.push(arr.slice(i, i + N));
    }
    return result
}
